﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Threading;
using ICSharpCode.AvalonEdit;
using Microsoft.Xaml.Behaviors;

namespace YJTTool.Common.Controls
{
    public sealed class AvalonEditBinder : Behavior<TextEditor>
    {
        public static readonly DependencyProperty InputTextProperty =
        DependencyProperty.Register("InputText", typeof(string), typeof(AvalonEditBinder),
        new FrameworkPropertyMetadata(default(string), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null));

        public string InputText
        {
            get { return (string)GetValue(InputTextProperty); }
            set { SetValue(InputTextProperty, value); }
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            if (AssociatedObject != null)
            {
                AssociatedObject.TextChanged += AssociatedObjectOnTextChanged;
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            if (AssociatedObject != null)
            {
                AssociatedObject.TextChanged -= AssociatedObjectOnTextChanged;
            }
        }

        private void AssociatedObjectOnTextChanged(object sender, EventArgs eventArgs)
        {
            var textEditor = sender as TextEditor;
            if (textEditor != null)
            {
                if (textEditor.Document != null)
                {
                    InputText = textEditor.Document.Text;
                }
            }
        }
        private static readonly HashSet<TextEditor> _updatingEditors = new HashSet<TextEditor>();

        public static readonly DependencyProperty TextProperty =
            DependencyProperty.RegisterAttached(
                "Text",
                typeof(string),
                typeof(AvalonEditBinder),
                new FrameworkPropertyMetadata(
                    default(string),
                    FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                    OnTextPropertyChanged));

        private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is not TextEditor editor) return;

            // 防止重复更新
            if (_updatingEditors.Contains(editor)) return;

            // 处理跨线程调用
            if (editor.Dispatcher.CheckAccess())
            {
                UpdateDocument(editor, e.NewValue as string);
            }
            else
            {
                editor.Dispatcher.BeginInvoke(
                    DispatcherPriority.Normal,
                    new Action(() => UpdateDocument(editor, e.NewValue as string)));
            }
        }

        private static void UpdateDocument(TextEditor editor, string newText)
        {
            try
            {
                _updatingEditors.Add(editor);

                // 标准化换行符
                newText = NormalizeNewLines(newText);

                // 优化性能：仅当内容不同时更新
                if (editor.Document.Text != newText)
                {
                    var offset = editor.CaretOffset;
                    editor.Document.Text = newText ?? string.Empty;
                    editor.CaretOffset = ClampCaretOffset(offset, newText);
                }
            }
            finally
            {
                _updatingEditors.Remove(editor);
            }
        }

        private static string NormalizeNewLines(string text)
        {
            return text?
                .Replace("\r\n", "\n")  // 统一为 Unix 风格
                .Replace("\r", "\n");   // 处理旧版 Mac 换行符
        }

        private static int ClampCaretOffset(int offset, string text)
        {
            if (string.IsNullOrEmpty(text)) return 0;
            return Math.Min(offset, text.Length);
        }

        public static string GetText(DependencyObject obj)
        {
            return (string)obj.GetValue(TextProperty);
        }

        public static void SetText(DependencyObject obj, string value)
        {
            obj.SetValue(TextProperty, value);
        }
    }
}
